package 示例代码.sence;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 小廖长得很漂亮，有10个追求者。
 * 10个追求者同时不停给小廖送花，
 * 谁的花束让小廖满意，小廖就打算嫁给谁。
 * 小廖满意的花束的花瓣数每10毫秒在1000内随机变化一次。
 * 追求者每毫秒猜测并赠送一次
 * 请用多线程模拟以上场景，计算出小廖的未来老公是谁。
 * @author SunAo
 * @date 2020/7/16 11:27
 */
public class XiaoLiaoXuanFu {

    final static int MAX = 1000;
    final static Liao liao = new Liao();

    static class Liao implements Runnable{
        private AtomicInteger like = new AtomicInteger(0);
        @Override
        public void run() {
            Random random = new Random();
            while(true){
                like.getAndSet(random.nextInt(MAX));
                System.out.println("now like is :"+like.get());
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) { e.printStackTrace(); }
            }
        }
        public void recive(String name,Integer flower){
            System.out.println("Name:"+name+",recive:"+flower);
            if(like.get() == flower.intValue()){
                System.out.println("Name:"+name+",you are my boy");
                System.exit(0);
            }
        }
    }

    static class Boy implements Runnable{

        @Override
        public void run() {
            while(true){
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) { e.printStackTrace(); }
                int flower = new Random().nextInt(MAX);
                liao.recive(Thread.currentThread().getName(),flower);
            }
        }
    }


    public static void main(String[] args) {
        new Thread(liao).start();
        for (int i = 0; i < 10 ; i++) {
            Thread thread = new Thread(new Boy(),"Boy - "+i);
            thread.start();
        }
    }
}
